var scale = .0003;

var arrayColors = {};
var map;
var ptCenter;
var refresh = 0;
var mapGsize = 200;
var geoCoder;
var userColor;
var userId = 0;
var homeBaseId;
var homeBaseMarker;
var cityId;

var squareTwo = Math.sqrt(2);
var usersName = [];
var strColor = "white";
var clock;



var limits;
var homeBaseCoords = new Array();
var active = false;   
var centralPoint = new POINT(105, 78);
var myCurrentPoint;
var orginalPoint;
var ableTOChallenge = [];



arrayColors[0] = 'black'
arrayColors[1] = 'white';


var hexagonMap = new Array();
var matrix = [];
var coins = [];
var coordinatesIds = [];
var printed = [];


for(var i=0; i<mapGsize; i++) {
    //matrix[i] = new Array(mapGsize);
    coins[i] =  new Array(mapGsize);
    coordinatesIds[i] = new Array(mapGsize);
    printed[i] = new Array(mapGsize);
    
}


for(var i= 0 ; i<mapGsize; i++)
{
    for(var j = 0; j<mapGsize; j++){
       // matrix[i][j] = 0;
        coins[i][j] = 0;
        coordinatesIds[i][j] = 0;
        printed[i][j] = 0;
        
    }
}




var styleArray = [{"featureType":"water","stylers":[{"color":"#021019"}]},{"featureType":"landscape","stylers":[{"color":"#08304b"}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#0c4152"},{"lightness":5}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#000000"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#0b434f"},{"lightness":25}]},{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"color":"#000000"}]},{"featureType":"road.arterial","elementType":"geometry.stroke","stylers":[{"color":"#0b3d51"},{"lightness":16}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#000000"}]},{"elementType":"labels.text.fill","stylers":[{"color":"#ffffff"}]},{"elementType":"labels.text.stroke","stylers":[{"color":"#000000"},{"lightness":13}]},{"featureType":"transit","stylers":[{"color":"#146474"}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#000000"}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#144b53"},{"lightness":14},{"weight":1.4}]}];



function INDEX(line, column)
{
    this.left = line;
    this.right = column;
    
}


function getTen()
{
    return Math.floor( Math.random()*100%7);

}


function POINT(l,r){
    
    var leftValue = Math.floor(l*10000);
    var rightValue = Math.floor(r*10000);
    
    this.l = leftValue/10000;
    this.r = rightValue/10000;
    
    
};

function getCurrentLocation(){
    

    
    getCity();
}


function HEX(ptCenter)
{
 
    var correction = 0.0001;
    
    var pointSum        = Math.round(  100000*(ptCenter.l+scale/2)   )/100000;
    var pointNormal     = Math.round(  100000*ptCenter.l             )/100000;
    var pointMinus      = Math.round(  100000*(ptCenter.l-scale/2)   )/100000 ;
    
    var pointRightSum = Math.round( 100000*( ptCenter.r+ (scale )/2   )  )/100000 ;
    
    var pointRightMinus =  Math.round( 100000*( ptCenter.r- (scale )/2   )  )/100000;
    
    
    this.first =    new google.maps.LatLng( pointNormal ,   Math.round( 100000*( ptCenter.r+ (scale   )   )  )/100000 );
    this.second=    new google.maps.LatLng( pointSum    ,   pointRightSum                       );
    this.third =    new google.maps.LatLng( pointSum    ,   pointRightMinus                  );
    this.forth =    new google.maps.LatLng( pointNormal ,   Math.round( 100000*( ptCenter.r- (scale )     )  )/100000 );
    this.fifth =    new google.maps.LatLng( pointMinus  ,   pointRightMinus     );
    this.sixth =    new google.maps.LatLng( pointMinus  ,   pointRightSum    );

};



function LIMITS(lineIn, lineOut, columnIn, ColumnOut)
{
    this.lineInit = lineIn - 10;
    this.lineEnd = lineOut + 10;
    this.columnInit = columnIn -10 ;
    this.columnEnd = ColumnOut + 10;
    
    if(this.lineInit < 0)
        this.lineInit = 0;
    
     if(this.columnInit < 0)
        this.columnInit = 0;
    
     if(this.lineEnd >= mapGsize)
        this.lineEnd = mapGsize;
    
     if(this.columnEnd  >= mapGsize)
        this.columnEnd = mapGsize;

};



function setUserId(userId)
{
    //$.cookie('userId', userId, { expires: 365 });
    
    try{
        intel.xdk.cache.setCookie('userId',userId,365);
    }
    catch(e)
    {
     $.cookie('userId', userId, { expires: 365 });
    }
}

function getUserId()
{
 
    
    try{
        
    if(userId == 0)
        userId =  intel.xdk.cache.getCookie('userId');
        
        
        
    }
    catch(e)
    {  
        userId = $.cookie('userId');
    }
    
    
    if(userId == undefined)
        return 3;
    
    return parseInt(userId);
}



function getUrlServlet()
{
    return "http://149.210.188.153/hexar";
    
}
function printUserData(userId)
{
   
    
        var urlAjax = getUrlServlet() + "/utf?method=getCoordinates&userId="+userId;
		var header = "application/x-www-form-urlencoded;charset=utf-8"
		var type = "GET";
		$.ajax({
			url : urlAjax,
			type : type,
			dataType : 'JSON',
			contentType : header,
            async: false,
			encoding : "utf-8",
			error : function(data, status, jqx) {
				
			},
			success : function(data, status, jqx) {
			   
               
                var hexagons = data.hexagons;
            
                
                for(var i in hexagons)
                {
                    var index = hexagons[i].index;
                    
                    matrix[ param(index.line, index.column) ] = userId;
                    
                    
                    coins[index.line][index.column] = hexagons[i].coins;
                    coordinatesIds[index.line][index.column] = hexagons[i].Id;
                    
                }
                
            }
		});
    
}



function param(left, right)
{
    
    return left+";"+right;
}


function getPlayers(city)
{
 
    
        var urlAjax = getUrlServlet() + "/utf?method=getUsersFromCity&cityId="+city;
		var header = "application/x-www-form-urlencoded;charset=utf-8"
		var type = "GET";
		$.ajax({
			url : urlAjax,
			type : type,
			dataType : 'JSON',
			contentType : header,
            async: false,
			encoding : "utf-8",
			error : function(data, status, jqx) {
				
			},
			success : function(data, status, jqx) {
			   
             
             for(i in data)
             {
                var user = data[i];
                arrayColors[user.id] = user.color;
                usersName[user.id] = user.name;
                if(user.id != getUserId())
                {
                    printUserData(user.id);
                    
                }
             
             
             }
                
            }
		});
    
    
}

function chooseYourColor()
{
        
    $( "#popUpColor" ).css(   "visibility", "visible");     
    /*$( "#popUpColor" ).css( "background-color", "#1a344b" );*/
    $( "#popUpColor" ).css( "opacity", "0.9" );
            
            $(  "#popUpColor").dialog({
                modal: true,
                maxWidth: 300,
                maxHeight: 320, 
                /*draggable: false,
                position: 'center',*/
                open: function (event, ui) {
                    $('#popUpColor').css('overflow', 'hidden'); //this line does the actual hiding
                },
                
                close: function()
                {
                    
                
                    
                    
                }
            });
    
    
    
    
}






function storeCoords(hexagon, left, right)
{
    var vertices = hexagon.getPath();
    var contentString = "";
    var vertice;
    for (var i =0; i < vertices.getLength(); i++) {
        var xy = vertices.getAt(i);
        contentString +=Math.round( 10000*xy.lat())/10000 + ',' + Math.round( xy.lng() *10000)/10000 + ";";
        
        
    }   
    
    var city = getCityId();
    
  
  
        var urlAjax = getUrlServlet() + "/utf?method=putFlag&userId="+getUserId()+"&coordinates=" + contentString + "&cityId=" + city+"&index=" + left + ","+right;
		var header = "application/x-www-form-urlencoded;charset=utf-8"
		var type = "GET";
		$.ajax({
			url : urlAjax,
			type : type,
            async: false,
			dataType : 'JSON',
			contentType : header,
            
			encoding : "utf-8",
			error : function(data, status, jqx) {
				
			},
			success : function(data, status, jqx) {
                
                
                coordinatesIds[left][right] = data.coordId;
                
                
                if(data.isHomeBase )
                {
                   
                   homeBaseId = data.coordId;
                   
                   var vertice =  vertices.getAt(0);
                  
                  var rightCorrection = 0.00017;
                    var leftCorrection = 0.00015;
                   var myLatlng = new google.maps.LatLng(vertice.lat()-leftCorrection, vertice.lng()-rightCorrection); 
                   
                   coins[left][right] = 5;

                   var marker = new MarkerWithLabel({
                      position: myLatlng,
                      draggable: false,
                      raiseOnDrag: true,
                      map: map,
                      size: new google.maps.Size(40, 40),
                      labelContent: coins[left][right]+'',
                      labelAnchor: new google.maps.Point(40, 40),
                      labelClass: "homebase",
                      labelStyle: {opacity: 1.0},
                      icon: "http://placehold.it/1x1",
                      visible: true
                   });
                    
                    clock.setTime(60);
                    clock.setCountdown(true);
                    clock.start();
                    
                    
                  homeBaseMarker = marker;
                    
                   google.maps.event.addListener( marker, 'click', function(){ moveCoins(hexagon,this, left, right); }); 
                }
               
               

			
			}
		});
  

    
}

var tempPoly;
var tempLine;
var tempColumn;
var tempMarker;


function updateCoordinates(orign, target, value )
{
    
  
    
        var urlAjax = getUrlServlet() + "/utf?method=updateCoins&orign="+orign+"&target="+target+"&coin="+value;
		var header = "application/x-www-form-urlencoded;charset=utf-8"
		var type = "POST";
		$.ajax({
			url : urlAjax,
			type : type,
			dataType : 'JSON',
			contentType : header,
            async: true,
			encoding : "utf-8",
			error : function(data, status, jqx) {
				
			},
			success : function(data, status, jqx) {
			   
              
                
            }
		});
  
    
    
}


function moveCoins(poly,marker,  line, column)
{
    
  
    
    if(active)
    {
       
        if(coins[line][column] > 9)
        {
            alert("You can't move your points here. Each hexagon must have less than 10 points")  ;
        }
        else
        {
        
           if( tempLine == line && tempColumn == column )
           {
               tempPoly.setOptions({strokeColor: strColor, fillColor: userColor});
               active = false;
           }
           else
           {
                var move=confirm("Do you want to move your points here?");
                if(move)
                {
                    active = false;
                    tempPoly.setOptions({strokeColor: strColor, fillColor: userColor});

                    coins[tempLine][tempColumn] = coins[tempLine][tempColumn] -1;
                    coins[line][column] = coins[line][column] + 1;
                    tempmarker.setOptions({labelContent: coins[tempLine][tempColumn]+'',});
                    marker.setOptions({labelContent: coins[line][column]+'',});
                    updateCoordinates( coordinatesIds[tempLine][tempColumn], coordinatesIds[line][column], 1);

                }
            }
        }
        
        
    }
    else{
        
        if(coins[line][column] <= 1)
        {
            alert("You can't move your points here. Each Hexagon must have more than 1 points")  ;
        }
        else
        {
            active = true;
            poly.setOptions({strokeColor: strColor, fillColor: 'blue'});
            tempPoly = poly;
            tempLine = line;
            tempColumn = column;
            tempmarker = marker;
        }
    }
    
}


function updateLimits(left, right)
{
    var beginLine = left - 10;
    var endLine = left + 10;
    var beginColumn = right - 10;
    var endColumn = right + 10;

    if(beginLine < 0)
        beginLine = 0;
    if(beginColumn < 0)
        beginColumn = 0;
    
    if(endLine >= mapGsize)
        endLine = mapGsize -1;
    if(endColumn >= mapGsize)
        endColumn = mapGsize -1;
    

    if(limits.lineInit > beginLine)
        limits.lineInit = beginLine;

    if(limits.lineEnd < endLine)
        limits.lineEnd = endLine;

    if(limits.columnInit > beginColumn)
    if(limits.columnInit > beginColumn)
        limits.columnInit = beginColumn;

    if(limits.columnEnd < endColumn)
        limits.columnEnd = endColumn;

    showHexagonsInTheMap();

}



function getHexagonCoordinates(i, j)
{
     var parameter = i +";" +j ;
     var  hex =  hexagonMap[parameter] ;
     if(hex != undefined)
     {
         
        var vertice = hex.getPath().j[0];
        var rightCorrection = 0.00017;
        var leftCorrection = 0.00015;
        
        var myLatlng = new google.maps.LatLng(vertice.lat()-leftCorrection , vertice.lng()+rightCorrection);
        return myLatlng;
        
     }
    
    return undefined;
}




function showHexagonsInTheMap()
{
    for(var i = limits.lineInit ; i < limits.lineEnd ; i++){

        for(var j=  limits.columnInit; j < limits.columnEnd; j++)
        {
          
            if( printed[i][j] == 0)
            {
                var parameter = i +";" +j ;
                var  hex =  hexagonMap[parameter] ;
                
                if(hex == undefined)
                {
                    //hex = createHexagon(i, j);
                    
                   
                    
                }
                else
                {
                    hex.setMap(map);
                    printed[i][j] = 1;
                    
                    var userHexagon =  matrix [ parameter ];
                    if(userHexagon == undefined)
                        userHexagon = 0;
                    
                    
                    if( userHexagon> 1 && userHexagon != getUserId())
                    {
                        var vertice = hex.getPath().j[0];
                        var leftCorrection = 0.00015;
                        var rightCorrection = 0.00017;
                        var myLatlng = new google.maps.LatLng(vertice.lat()-leftCorrection, vertice.lng()-rightCorrection);
                        
                        addMarkerListener(myLatlng, hex, i, j);
                        
                    }
                    
            }
            }

        }

    }
    
                                   
   
    
    

}
function addMarkerListener(myLatlng, hexagon,left, right )
{
     
        var newMarker = new MarkerWithLabel({
                            position: myLatlng,
                            draggable: false,
                            raiseOnDrag: false,
                            map: map,
                            size: new google.maps.Size(40, 40),
                            labelContent: coins[left][right]+'',
                            labelAnchor: new google.maps.Point(40, 40),
                            labelClass: "labels", // the CSS class for the label
                            labelStyle: {opacity: 1.0},
                            icon: "http://placehold.it/1x1",
                            visible: true
                        });
                        
            
            google.maps.event.addListener( newMarker, 'click',  function(){
         
                        
                        challenge(this, hexagon, left, right ); 
                                             
                                             
                }); 
           
     
    
}


function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function plantFlag(poly,lValue, rValue){
   
   
    if(active )
    {
    
        var stay=confirm("Do you want to expand your territory?");

        if (stay)
        {
            
            var HexagonUserId = matrix[param(lValue, rValue)];

          
            if(HexagonUserId == undefined)
                HexagonUserId = 0;
            
            
           if(HexagonUserId == 1)
           {
               
               storeCoords(poly, lValue, rValue);
               matrix[param(lValue, rValue)] = getUserId();
               
               var vertice = poly.getPath().j[0];
                var leftCorrection = 0.00015;
                var rightCorrection = 0.00017;
               active = false;
               poly.setOptions({strokeColor: strColor, fillColor: userColor, fillOpacity: 0.45});
               google.maps.event.clearListeners(poly, 'click');
    
               if(tempLine != undefined )
               {
                  
                   var myLatlngMarker = new google.maps.LatLng(vertice.lat()-leftCorrection, vertice.lng()-rightCorrection);

                   updateLimits(lValue, rValue);
                   coins[lValue][rValue] = 1;
                   
                   coins[tempLine][tempColumn] = coins[tempLine][tempColumn] -1;
                   tempmarker.setOptions({labelContent: coins[tempLine][tempColumn]+'',});
                   tempPoly.setOptions({strokeColor: strColor, fillColor: userColor});

                   
 
                   var marker = new MarkerWithLabel({
                      position: myLatlngMarker,
                      draggable: false,
                      raiseOnDrag: false,
                      map: map,
                      size: new google.maps.Size(40, 40),
                      labelContent: coins[lValue][rValue]+'',
                      labelAnchor: new google.maps.Point(40, 40),
                      labelClass: "labels", // the CSS class for the label
                      labelStyle: {opacity: 1.0},
                      icon: "http://placehold.it/1x1",
                      visible: true
                   });

                   google.maps.event.addListener( marker, 'click', function(){ moveCoins(poly,this, lValue, rValue); }); 
                   
                   updateCoordinates(coordinatesIds[tempLine][tempColumn], coordinatesIds[lValue][rValue], 1 )  ;
               
              
               }
               

           }
            setBlackHexagons(lValue, rValue);



       }
    }
    
}



function fight(player1, player2)
{
            $( "#iframeDice" ).css(   "width", "320px");
            $( "#iframeDice" ).css(   "height", "240px");
            $( "#popUpDice" ).css(   "visibility", "visible");
           
            
            $(  "#popUpDice").dialog({
                modal: true,
                width: 400,
                height: 320, 
                
                close: function()
                {
                   
                    var player1 = returnResult[0];
                    var player2 = returnResult[1];
                    
                    var p1Left = parseInt(player1.index.split(";")[0]); 
                    var p1Right =  parseInt(player1.index.split(";")[1]); 
                        
                    var p2Left = parseInt(player2.index.split(";")[0]); 
                    var p2Right =  parseInt(player2.index.split(";")[1]); 
                
                    
                    if( player2.units == 0)
                    {
                         coins[p1Left][p1Right] = player1.units;
                         tempmarker.setOptions({labelContent: coins[p1Left][p1Right]+'',});
                         updateCoordinates( coordinatesIds[p1Left][p1Right] , 0, coins[p1Left][p1Right] );
                        
                        removeHexagon(coordinatesIds[p2Left][p2Right] );
                        
                        coins[p2Left][p2Right] = 0;
                        coordinatesIds[p2Left][p2Right] = 0;
                        player2.marker.setMap(null);
                        
                        matrix[param(p2Left, p2Right)] = undefined;
                        fillNeighborHexagon(p2Left, p2Right);
                        
                        
                       // matrix[p2Left][p2Right] = 0
                        ableTOChallenge[p2Left +";"+p2Right] = 0;
                        
                        
                        
                        
                    }
                    else
                    {
                        
                        coins[p1Left][p1Right] = player1.units;
                        coins[p2Left][p2Right] = player2.units;
                        tempmarker.setOptions({labelContent: coins[p1Left][p1Right]+'',});
                        player2.marker.setOptions({labelContent: coins[p2Left][p2Right]+'',});
                        
                        updateCoordinates( coordinatesIds[p1Left][p1Right] , 0, coins[p1Left][p1Right] );
                        updateCoordinates( coordinatesIds[p2Left][p2Right] , 0,  coins[p2Left][p2Right] );
                        
                    }
                    tempPoly.setOptions({strokeColor: strColor, fillColor: userColor});
                    active = false;
                  
                    
                    
                }
                
            });
            dice(player1, player2);
    
    
}
/*
 var player1 = {id:getUserId(), name: 'Chabersworth', units:1},
     player2 = {id:getUserId(), name: 'xxProMlgNoScope69xx', units:1};  

*/
function challenge(marker, hexagon,  left, right)
{
    
    //var enemy = matrix[left][right];
    var enemy = matrix[param(left, right)];
    
   
    if(active && ableTOChallenge[left+";"+right] == 1)
    {
        var fightStarted = confirm("Do you want to fight?");
    
        if(fightStarted)
        {
            
            var player1 = {id:getUserId(),  name: usersName[getUserId()], units:coins[tempLine][tempColumn], marker: tempMarker, index: tempLine +";"+tempColumn};
            var player2 = {id:enemy,        name: usersName[enemy]      , units:coins[left][right]          , marker: marker,    index: left+";"+right};  
           try{
               songBattle();
           }catch(e)
           {
            console.log(e)
           
           }
            fight(player1, player2);
           
            
        }

            
    }
    

    
}


function fillNeighborHexagon(lValue, rValue)
{
   // if( matrix[lValue][rValue] == 0){
    
    if(matrix[param(lValue, rValue)] == undefined){
                var nvalue = lValue;
                var hex =   hexagonMap[nvalue+';'+rValue];
                hex.setOptions({strokeColor: strColor, fillColor: arrayColors[1], fillOpacity: 0.2});
                matrix[param(lValue, rValue)] = 1
                // matrix[lValue][rValue] = 1;
                google.maps.event.addListener(hex, 'click', function(){       plantFlag(this, lValue, rValue);     }); 

    }else
    {
        
          
        if( matrix[param(lValue, rValue)] != getUserId())
        {
            ableTOChallenge[lValue +";"+rValue] = 1;
            
        }
        
    }
    
}


function removeHexagon(hexagonid)
{
    
      
        var urlAjax = getUrlServlet() + "/utf?method=loseHexagon&hexagon="+hexagonid;
		var header = "application/x-www-form-urlencoded;charset=utf-8"
		var type = "POST";
		$.ajax({
			url : urlAjax,
			type : type,
			dataType : 'JSON',
			contentType : header,
            async: true,
			encoding : "utf-8",
			error : function(data, status, jqx) {
				
			},
			success : function(data, status, jqx) {
			   
              
                
            }
		});
  
 
    
}


function setBlackHexagons(lValue, rValue)
{
        
    fillNeighborHexagon(lValue+1,rValue);
    
    
    fillNeighborHexagon(lValue,rValue+1);
    fillNeighborHexagon(lValue-1,rValue);
    fillNeighborHexagon(lValue+1,rValue);
    fillNeighborHexagon(lValue,rValue-1);
           
    if( lValue%2 == 0 )
    {
        
        fillNeighborHexagon(lValue-1,rValue-1);
        fillNeighborHexagon(lValue+1,rValue-1); 


    }
    else{
        
        fillNeighborHexagon(lValue-1,rValue+1);
        fillNeighborHexagon(lValue+1,rValue+1);
       

    }


    
}




function showArrays(polygn) {

  var vertices = polygn.getPath();
  var colors =userColor;

  var   hexagon = new google.maps.Polygon({
             paths: vertices,
             strokeColor: strColor,
             strokeOpacity: 0.3,
             strokeWeight: 2,
             fillColor: colors,
             fillOpacity: 0.45,
             clickable:true
            
         });
    
    hexagon.setMap(map);
 
}


function getPoints()
{
    
      var lineHome = homeBaseCoords[0];
      var columnHome =  homeBaseCoords[1];
                            
    if(coins[lineHome][columnHome] < 9 )
    {
        $("#pointsimg").hide("slow");     
        coins[lineHome][columnHome] =  coins[lineHome][columnHome] + 2;
        checkTimeHomebase(homeBaseId);
        homeBaseMarker.setOptions({labelContent: coins[lineHome][columnHome]+'',});
                                
    }
    
}



function setHexagon(point, i, l)
{
    
    var hexagon;
    var hexagonPoints;
    
    var hexCoords;
    
    hexagonPoints = new HEX(point);
        
        hexCoords = [
            hexagonPoints.first,
            hexagonPoints.second, 
            hexagonPoints.third,
            hexagonPoints.forth, 
            hexagonPoints.fifth, 
            hexagonPoints.sixth 
        ];
            
    
        
     var hexagonUserId = matrix[param(i,l)];
      
        
      if(hexagonUserId == undefined){
          hexagonUserId = 0;
      }
      var colors =  arrayColors[hexagonUserId];
    
     
        hexagon = new google.maps.Polygon({
             paths: hexCoords,
             strokeColor: strColor,
             strokeOpacity: 0.3,
             strokeWeight: 2,
             fillColor: colors,
             fillOpacity: 0.45,
             clickable:true,
            
            
         });
    
        if(colors == arrayColors[1])
        {
            hexagon.setOptions({fillOpacity: 0.2});
            google.maps.event.addListener(hexagon, 'click', function(){ plantFlag(this, i, l);  }); 
            
        }
    
         var leftCorrection = 0.00015;
         var rightCorrection = 0.00017;
       
        
        var myLatlng = new google.maps.LatLng(point.l-leftCorrection, point.r+ rightCorrection); 
        if(hexagonUserId == getUserId())
        {
            
            updateLimits(i , l);
            
            var marker = new MarkerWithLabel({
                  position: myLatlng,
                  draggable: false,
                  raiseOnDrag: false,
                  map: map,
                  size: new google.maps.Size(40, 40),
                  labelContent: coins[i][l]+'',
                  labelAnchor: new google.maps.Point(40, 40),
                  labelClass: "labels", // the CSS class for the label
                  labelStyle: {opacity: 1.0},
                  icon: "http://placehold.it/1x1",
                  visible: true
               });
             
             if(coordinatesIds[i][l] == homeBaseId)
             {
                 marker.setOptions({labelClass: 'homebase'});
                homeBaseMarker = marker;
             }  
                 
             google.maps.event.addListener( marker, 'click', function(){ moveCoins(hexagon,this, i, l);   }); 
            
        }
     

        hexagonMap[i+';'+l]  = hexagon;

}


function  setBlackOrUserFlag(i, j, cArray){
    
    var parameter = i+";"+j;
    
    var userHexagon = matrix[parameter];
    if(userHexagon == undefined)
    {
        userHexagon = 0;
    }
    
    if(cArray.indexOf(parameter) == -1)
    {
        if(userHexagon == getUserId() )
        {

            cArray.push(parameter);
           
            setBlackOrUserFlag((i+1)  , j  , cArray);
            setBlackOrUserFlag(i    , (j+1), cArray);
            setBlackOrUserFlag((i-1)  , j  , cArray);
            setBlackOrUserFlag(i    , (j-1), cArray);
            
            if( i%2 == 0 )
            {
                setBlackOrUserFlag((i-1),(j-1), cArray);
                setBlackOrUserFlag((i+1),(j-1), cArray);
            }
            else{
               
                setBlackOrUserFlag((i-1),(j+1), cArray)
                setBlackOrUserFlag((i+1), (j+1), cArray);
            }

        }
        else{

           if( matrix[parameter] == undefined )
           {
               matrix[parameter] =1;
           
           }
            else
            {
                   ableTOChallenge[parameter] = 1;
            }
        }
    }
    
    
    
}


function getIndexByCoordinates(point)
{
    
        var x = orginalPoint.l - point.l;
        var y = orginalPoint.r - point.r;
        
    
        var Cx = x/0.000315;
        var Cy = y/0.00028;
    
        Cx = Math.round(Cx);
        Cy = Math.round(Cy);
        
        var i = centralPoint.l -  Cy;
        var j = centralPoint.r -  Cx;
    
       return new INDEX(i, j);
    
}





function setHexagonClicked()
{
   
    
    if(myCurrentPoint == undefined)
    {
        setTimeout(setHexagonClicked, 2000);
    
    }
    else{
    
        var x = orginalPoint.l - myCurrentPoint.l;
        var y = orginalPoint.r - myCurrentPoint.r;
        
    
        var Cx = x/0.000315;
        var Cy = y/0.00028;
    
        Cx = Math.round(Cx);
        Cy = Math.round(Cy);
        
        var i = centralPoint.l -  Cy;
        var j = centralPoint.r -  Cx;
        
        setBlackOrUserFlag(i, j, new Array());
       
        var  centerLating = getHexagonCoordinates(i,j);
        
        if(centerLating == undefined)
        {
            centerLating = new google.maps.LatLng( myCurrentPoint.l,  myCurrentPoint.r );
            
        }
        map.setCenter( centerLating);
        limits = new LIMITS(i, i, j, j);        
        buildMap();
        google.maps.event.addListener(map, 'center_changed', function() {
            var newCenter = map.getCenter();
            var newCenterPoint  =  new POINT(newCenter.lat(), newCenter.lng());
            var index =  getIndexByCoordinates(newCenterPoint);
            updateLimits(index.left, index.right);
            
        });
        
        $("#spinner").fadeOut("slow");
    
   
    } 
  
}
    


function buildMap(){
    
     
    var hexagon;
    var hexagonPoints;
    var point  = new POINT(ptCenter.l, ptCenter.r);
    var hexCoords;
    
    
   for(var l=0 ; l<mapGsize; l++)
   {
        
       point.l = ptCenter.l + scale*l;
       point.r = ptCenter.r;
      
       
       for (var i =0; i< mapGsize; i++)  {
          
         //if(matrix[param(i, l)]!= undefined)
        //  {
           
               var correction = 0.00003
               if(i%2 == 1)
               {
                    point.l = point.l +scale/2;
                    correction = 0.00002;
                }
               else{
                   point.l = point.l -scale/2;

               }

                point.r = point.r + squareTwo*scale +correction;

             
                setHexagon(point, i, l);
               
            //}

        }
        
    }
    showHexagonsInTheMap();
   
}

function createHexagon(left, right)
{
    
    var correction = 0.00003;
    var point  = new POINT(ptCenter.l, ptCenter.r);
    
    
    point.l = ptCenter.l + left*scale*l;
    point.r = ptCenter.r;
    
    
    if( left %2 ==1 ){
        correction = 0.00002;
    
    }else
    {
        
        
    }
    
    
    
}

function getUserCoords()
{
  
        var userId = getUserId();
    
        var urlAjax = getUrlServlet() + "/utf?method=getCoordinates&userId="+userId;
		var header = "application/x-www-form-urlencoded;charset=utf-8"
		var type = "GET";
		$.ajax({
			url : urlAjax,
			type : type,
			dataType : 'JSON',
			contentType : header,
            async: false,
			encoding : "utf-8",
			error : function(data, status, jqx) {
				
			},
			success : function(data, status, jqx) {
			   
               
                var hexagons = data.hexagons;
                if(hexagons.length < 1 )
                {
                    
                    chooseYourColor();
                    active = true;
                }
                
                for(var i in hexagons)
                {
                    var index = hexagons[i].index;
                    
                    matrix[param(index.line, index.column)] = userId;
                    coins[index.line][index.column] = hexagons[i].coins;
                    coordinatesIds[index.line][index.column] = hexagons[i].Id;
                    
                    if(hexagons[i].Id == homeBaseId)
                    {
                        homeBaseCoords.push(index.line);
                        homeBaseCoords.push(index.column);
                        
                    }
                    
                    
                }
                
            }
		});
  
    
}




function getCityName()
{
 
    var cityNameCookie;
    try{
        
        cityNameCookie = intel.xdk.cache.getCookie('City',userId,365);   
    }
    catch(e)
    {
        cityNameCookie =    $.cookie('City');
        
    }
    if(cityNameCookie == undefined)
        return "Zwolle";
    
    return cityNameCookie;
   
}


function getCity()
{
        var urlAjax = getUrlServlet() + "/utf?method=getSquareId&coordinate="+myCurrentPoint.l +";"+myCurrentPoint.r;
		var header = "application/x-www-form-urlencoded;charset=utf-8"
		var type = "GET";
		$.ajax({
			url : urlAjax,
			type : type,
			dataType : 'JSON',
			contentType : header,
			encoding : "utf-8",      
            async: false,
			error : function(data, status, jqx) {
				
			},
			success : function(data, status, jqx) {
				
            
                try{
                    
                       // intel.xdk.cache.setCookie('city_id',data.Id,365);
                        cityId = data.Id;
                        
                        getPlayers(data.Id);
                    
                    
                }catch(e)
                {
                    $.cookie('city_id', data.Id, { expires: 365, path: '/' });
                    
                    getPlayers(data.Id);
                    
                }
                
                executeMap(data.centerPoint)
                checkinHomeBase();

                
			}
		});
    
}


function getCityId()
{
    
        return cityId;
   /* try{
        return intel.xdk.cache.getCookie('city_id',userId,365);   
        
    }catch(e)
    {
        return $.cookie('city_id');
    
    }*/
    
    
}


function executeMap(position){

   
    ptCenter = new POINT(position.left, position.right);  
    var latlng = new google.maps.LatLng(ptCenter.l, ptCenter.r);
    orginalPoint = new POINT(position.left, position.right);  
    var mapOptions = {
        zoom: 17,
        zoomControl: false,
        maxZoom:17,
        minZoom:17,
        streetViewControl: false,
        scrollwheel: false,
        panControl: false,
        mapTypeControl: false,
        disableDoubleClickZoom: true,
        center: new google.maps.LatLng(ptCenter.l, ptCenter.r),
        mapTypeId: google.maps.MapTypeId.MAPS,
        styles: styleArray
        
    };

    ptCenter.l = ptCenter.l - 80*scale;
    ptCenter.r = ptCenter.r - 150*scale;

    map = new google.maps.Map(document.getElementById('map-canvas'),  mapOptions);

    setHexagonClicked();
    
    
}

function setCurrentCity(position)
{
    myCurrentPoint = new POINT(position.coords.latitude, position.coords.longitude);
   
    var  pt = new POINT(position.coords.latitude, position.coords.longitude);
    
    var latlng = new google.maps.LatLng(pt.l, pt.r);
    var geo = new google.maps.Geocoder();
    geo.geocode({'latLng': latlng}, function(results, status) {
    
            var city = results[0].address_components[2].long_name;
           
        
        try
        {
            intel.xdk.cache.getCookie('City',city,365);  
        }catch(e)
        {
            $.cookie('City', city, { expires: 365, path: '/' });
        }

    });
    
    getCity();
}


function checkinHomeBase()
{
    var urlAjax = getUrlServlet() + "/utf?method=checkinHomeBase&userId="+getUserId()+"&cityId="+getCityId();
		var header = "application/x-www-form-urlencoded;charset=utf-8"
		var type = "GET";
		$.ajax({
			url : urlAjax,
			type : type,
			dataType : 'JSON',
			contentType : header,
            async: false,
			encoding : "utf-8",
			error : function(data, status, jqx) {
				
			},
			success : function(data, status, jqx) {
			
               
               if(data.coordId != 0)
               {
                    if(data.timeLeft > 0)
                    {
                        clock.setTime(data.timeLeft);
                        clock.setCountdown(true);
                        clock.start();

                    }else
                    {

                          $("#pointsimg").show("slow");
                    }
                
               }
                
                
               homeBaseId = data.coordId;
                

             }
		});
    
    
}



function setHomeBaseCenter()
{
    
    var  centerLating = getHexagonCoordinates(homeBaseCoords[0],homeBaseCoords[1]);
        
    if(centerLating == undefined)
    {
        centerLating = new google.maps.LatLng( myCurrentPoint.l,  myCurrentPoint.r );
            
    }
       
        
        
    map.setCenter( centerLating);
    
    
    
}


function getUserData(){
        
    var urlAjax = getUrlServlet() + "/utf?method=getUserData&userId="+getUserId();
		var header = "application/x-www-form-urlencoded;charset=utf-8"
		var type = "GET";
		$.ajax({
			url : urlAjax,
			type : type,
			dataType : 'JSON',
			contentType : header,
            async: false,
			encoding : "utf-8",
			error : function(data, status, jqx) {
				
			},
			success : function(data, status, jqx) {
			   
                userColor = data.color;
                
            
            }
		});
    
}


 function setUserColor(color)
{
            var urlAjax = getUrlServlet() + "/utf?method=updateColor&userId="+getUserId()+"&color="+color;
		      var header = "application/x-www-form-urlencoded;charset=utf-8"
              var type = "POST";
    $.ajax({
			url : urlAjax,
			type : type,
			dataType : 'JSON',
			contentType : header,
            async: false,
			encoding : "utf-8",
			error : function(data, status, jqx) {
				
			},
			success : function(data, status, jqx) {
			
               
             }
		});
            
            
}



  var userColorHomeBase;
        
        function chooseColor(color)
        {
            
            $("#currentColor").html('<div class = "imgChoose"  style=" background-image: url(img/colors/'+color+'.png);" onclick="clean()" > </div>');
            userColorHomeBase = color;
        }
        
        
        function clean()
        {
            $("#currentColor").html('');
            userColorHomeBase = undefined;
                
        }
        

        
        function confirmChange()
        {
            if(userColorHomeBase != undefined)
            {
                $( "#popUpColor" ).dialog( "close" );
                userColor = userColorHomeBase;
                setUserColor(userColorHomeBase);
                alert("click  in the hexagon to set your homebase");
                
                var myLatLng = new google.maps.LatLng( myCurrentPoint.l-0.00145 , myCurrentPoint.r+0.00177                                   );
               
                
                
                var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
                var marker = new google.maps.Marker({
                  position: myLatLng,
                  map: map,
                  icon: 'http://149.210.188.153/hexar/Files/img/finger.png',
                   size: new google.maps.Size(8, 8)
                    
                });
                
                 google.maps.event.addListener( marker, 'click', function(){
                 
                        marker.setMap(null);
                        
                        
                 
                 }); 
                
                
              
                    
                
                
                
            }
        }

        function closeDlg(){
            $("#popUpColor").dialog("close");
        }


function checkTimeHomebase(homebaseId)
{
     var urlAjax = getUrlServlet() + "/utf?method=checkTime&homebase="+homebaseId;
	 var header = "application/x-www-form-urlencoded;charset=utf-8"
     var type = "GET";
   
    
    $.ajax({
			url : urlAjax,
			type : type,
			dataType : 'JSON',
			contentType : header,
            async: false,
			encoding : "utf-8",
			error : function(data, status, jqx) {
				
			},
			success : function(data, status, jqx) {
			     
                
                if(data.timeLeft > 0)
                {
                    clock.setTime(data.timeLeft);
                    clock.setCountdown(true);
                    clock.start();
                    
                }else
                {
                   
                      $("#pointsimg").show("slow");
                }
                
               
             }
		});
    
    
}

function initialize() {
    
    
     $("#pointsimg").hide("slow");
    
    
    clock = $('.clock').FlipClock({
                    clockFace: 'HourlyCounter',
                    autoStart: false,
                    callbacks: {
                        stop: function() {
                          
                          if(homeBaseId != undefined && homeBaseId != 0)
                          {
                             
                              $("#pointsimg").show("slow");
                           
                          }
                        }
                    }
                });
    getUserData();
    navigator.geolocation.getCurrentPosition(setCurrentCity);
   // getCurrentLocation();
    getUserCoords();
 
}



google.maps.event.addDomListener(window, 'load', initialize);